package docker_service

import (
	docker_client_v1 "github.com/docker/docker/client"
	"go.uber.org/zap"
	"virtual-resource-schedule-service/client/docker_client"
	"virtual-resource-schedule-service/global"
	"virtual-resource-schedule-service/model/docker_container"
)

type IDockerContainerService interface {
	CreateContainer(request *docker_container.DockerContainerRequest) (
		response *docker_container.DockerContainerResponse, err error)
	ContainerStart(request *docker_container.DockerContainerStartRequest) (
		response *docker_container.DockerContainerStartResponse, err error)
	ContainerStop(request *docker_container.DockerContainerStopRequest) (
		response *docker_container.DockerContainerStopResponse, err error)
}

type DockerContainerService struct {
	DockerClient *docker_client.DockerClient
}

func NewDockerContainerService(machineId string) *DockerContainerService {
	client := global.DockerClientWithOpsMap[machineId]
	if client == nil {
		// @TODO 获取Docker的基础信息
		// @TODO 根据服务器ID获取对应的Docker TCP
		// @TODO 这里有两点：
		// 1、部署的时候需要加入Certs认证，且只允许对应的IP访问
		// 2、需要将对应的证书加载到我们的部署容器上
		client, err := docker_client_v1.NewClientWithOpts(
			docker_client_v1.WithHost("tcp://192.168.186.139:18696"))
		if err != nil {
			zap.S().Error("New DockerClientWithOpts error", zap.Error(err))
			return nil
		}
		dockerClient := docker_client.NewDockerClient(client)
		global.DockerClientWithOpsMap[machineId] = dockerClient
		return &DockerContainerService{
			DockerClient: dockerClient,
		}
	}
	return &DockerContainerService{
		DockerClient: client,
	}
}

func (containerService *DockerContainerService) CreateContainer(
	request *docker_container.DockerContainerRequest) (
	response *docker_container.DockerContainerResponse, err error) {
	container, err := containerService.DockerClient.CreateDockerContainer(request)
	if err != nil {
		zap.S().Error("Create container error", zap.Error(err))
	}
	return container, err
}

func (containerService *DockerContainerService) ContainerStart(
	request *docker_container.DockerContainerStartRequest) (
	response *docker_container.DockerContainerStartResponse, err error) {
	start, err := containerService.DockerClient.DockerContainerStart(request)
	if err != nil {
		zap.S().Error("Start container error", zap.Error(err))
	}
	return start, err
}

func (containerService *DockerContainerService) ContainerStop(
	request *docker_container.DockerContainerStopRequest) (
	response *docker_container.DockerContainerStopResponse, err error) {
	stop, err := containerService.DockerClient.DockerContainerStop(request)
	if err != nil {
		zap.S().Error("Stop container error", zap.Error(err))
	}
	return stop, err
}
